<!--财务设置->凭证类别-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="business-big-box" style="margin:2px 8px;">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <!-- <a-col :span="2">
                            <div class="btns" @click="add">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="edit">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col> -->
                        <!-- <a-col v-if="dataSource.length == 0" :span="2">
                            <div class="btns" @click="pageList">
                                <a-icon class="btns-icon" type="check-square" />
                                <div class="btns-text">选择凭证类别</div>
                            </div>
                        </a-col> -->
                        <a-col :span="2" v-if="permissions.includes('category:save')">
                            <div class="btns" @click="handleSubmit">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('category:delete')">
                            <div class="btns" @click="removes">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="pageList">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div class="category-table-container">
                <section class="course-table-box" style="width:800px">
                    <a-table :columns="columns" :data-source="dataSource" :customRow="customClick" :pagination="false" :row-selection="{selectedRowKeys: selectedRowKeys,onChange: onSelectChange,}" bordered :scroll="{ x: 0, y: 500}" :loading="tableLoading">
                        <template v-for="item in editColumnsArray" :slot="item" slot-scope="text, record ,index">
                            <div :key="item">
                                <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" @change="onCellChange(index, item, arguments)" />
                            </div>
                        </template>
                    </a-table>
                </section>
                <div class="contextmenu-box">
                    <!-- 右键菜单 -->
                    <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                        <li @click="handleAdd()">新增行</li>
                        <li @click="remove()">删除行</li>
                        <!--  <li @click="handleCopy()">复制行</li> -->

                    </ul>
                </div>
            </div>

            <a-modal v-model="typeModel" title="凭证类别预设" centered width="480px" :closable="false">
                <a-radio-group v-model="radioGroup">
                    <a-radio :style="radioStyle" :value="1">
                        记账凭证
                    </a-radio>
                    <a-radio :style="radioStyle" :value="2">
                        收款凭证 付款凭证 转账凭证
                    </a-radio>
                    <a-radio :style="radioStyle" :value="3">
                        现金凭证 银行凭证 转账凭证
                    </a-radio>
                    <a-radio :style="radioStyle" :value="4">
                        现金收款凭证 现金付款凭证 银行收款凭证 银行付款凭证 转账凭证
                    </a-radio>
                    <a-radio :style="radioStyle" :value="5">
                        自定义
                    </a-radio>
                </a-radio-group>
                <template slot="footer">
                    <div>
                        <a-button type="primary" @click="checkeDemo">{{radioGroup==5?'确认':'保存'}}</a-button>
                    </div>
                </template>
            </a-modal>
        </div>
    </div>
</template>
<script>

import { mapState } from "vuex";
import { pageList, getDefault, save, deleteAccount } from "@/api/erp/category";
import editableCell from "./editTable/EditableCell"

export default {
    components: {
        editableCell
    },
    data() {
        const columns = [
            {
                title: "序号",
                align: "center",
                dataIndex: 'number',
                width: 50,
                customRender: (text, row, index) => {
                    return index + 1;
                }
            },
            {
                title: "凭证字",
                dataIndex: "classWord",
                key: "classWord",
                align: "left",
                scopedSlots: { customRender: 'classWord' }
            },
            // {
            //     title: "类别名称",
            //     dataIndex: "classMethod",
            //     key: "classMethod",
            //     align: "left",
            //     scopedSlots: { customRender: 'classMethod' }
            // },
            {
                title: "凭证类别",
                dataIndex: "className",
                key: "className",
                align: "left",
                scopedSlots: { customRender: 'className' }
            },
            {
                title: "限制类型",
                dataIndex: "limitType",
                key: "limitType",
                align: "left",
                scopedSlots: { customRender: 'limitType' }
            },
            {
                title: "限制科目",
                dataIndex: "accountingName",
                key: "accountingName",
                width: 280,
                ellipsis: true,
                align: "left",
                scopedSlots: { customRender: 'accountingName' }
            },
        ];

        return {
            typeModel: false,
            radioStyle: {
                display: 'block',
                width: '100%',
                height: '30px',
                lineHeight: '30px',
            },
            visible: false,
            tableLoading: false,
            top: 0,
            left: 0,
            columns,
            radioGroup: null,
            dataSource: [],
            selectedRowKeys: [],
            editColumnsArray: ['classWord', 'classMethod', 'className', 'limitType', 'accountingName'],
            isRouterAlive: true,
            dataSourceNumber: 12,//默认行数
            thisClickId: null,
            thisClickIndex: null,
            customClick: (record, index) => {
                return {
                    on: {
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            if (index <= this.dataSource.length) {
                                this.openMenu(e);
                                console.log('右键点击的', index);
                                this.thisClickId = record.id;
                                this.thisClickIndex = index;
                            }
                        },

                    }
                }
            },
        }
    },
    activated() {
        this.pageList();
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    mounted() {
        this.pageList();
    },
    watch: {
        visible(value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    methods: {
        reload() {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        openMenu(e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu() {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd() {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete() {
            //删除整行
            let _this = this;
            let numberId = this.thisClickIndex;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk() {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > _this.dataSourceNumber) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }

                    _this.reload();
                },
                onCancel() { },
            });
        },
        onCellChange(indexTable, dataIndex, val) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, val, indexTable);

            let value = val[0];
            let type = val[1] ? val[1] : '';

            if (dataIndex == 'accountingName') {
                //限制科目
                if (value) {
                    console.log(value.constructor == Object)
                    console.log(value.constructor == Array)

                    if (value.constructor == Object) {
                        target['accountingId'] = value.id;
                        target['accountingName'] = value.name;
                    } else if (value.constructor == Array) {

                        target['accountingName'] = value.map(o => o.name).join(',');
                        target['accountingId'] = value.map(o => o.id).join(',');
                    }
                } else {
                    target['accountingName'] = null;
                    target['accountingId'] = null;
                }

            } else {
                if (target) {
                    // target[dataIndex] = value;
                    // this.dataSource = dataSource;
                    this.$set(target, dataIndex, value)
                }
            }
            this.$nextTick(() => {
                this.dataSource = dataSource;
                console.log('明细数据：', this.dataSource)
                if (type != 'input') {
                    this.reload();
                }
            })

        },
        //获取默认凭证
        getDefaultCateGory() {
            this.dataSource = [];
            if (this.radioGroup == 5) {
                this.selectedRowKeys = [];
                for (let i = 0; i < this.dataSourceNumber; i++) {
                    this.dataSource.push({});
                }
            } else {
                getDefault({ classMethod: this.radioGroup }).then(res => {
                    if (res.code === 200) {
                        let data = res.data;

                        // const length = this.dataSourceNumber - [...res.data].length;
                        // for (let i = 0; i < length; i++) {
                        //     data.push({})
                        // }

                        for (let i = 0; i < data.length; i++) {
                            delete data[i].id;
                            delete data[i].createDate;
                        }
                        this.dataSource = data;
                        // let data = data.map(v => {
                        //     return { ...v, isLeaf: true, title: v.name, key: v.code }
                        // })
                        // this.treeData[0].children = data;
                        // console.log(data)
                    }
                })

                setTimeout(() => {
                    this.handleSubmit();
                }, 200)
            }
            this.reload();
            this.typeModel = false;

        },
        //获取凭证
        pageList() {
            this.tableLoading = true;
            pageList().then(response => {
                if (response.code === 200) {
                    this.tableLoading = false;
                    if (response.data.length < 1) {
                        this.typeModel = true;
                        this.dataSource = [];
                    } else {
                        for (let i = 0; i < response.data.length; i++) {
                            delete response.data[i].createDate;
                            response.data[i].key = response.data[i].id;
                        }

                        this.dataSource = response.data;
                    }
                }
            }).catch(error => { });
        },
        //选择默认模板
        checkeDemo() {
            if (this.radioGroup == null) {
                this.$message.warning('请选择凭证类别');
                return
            } else {
                this.getDefaultCateGory();
            }
        },
        handleSubmit() {
            let requestData = this.dataSource.filter(e => e.classWord != null);
            if (requestData.length < 1) {
                this.$message.warning('请填写凭证类别表');
                return;
            }
            for (let c = 0; c < requestData.length; c++) {
                if (requestData[c].classWord.length > 2) {
                    this.$message.warning(`第${c + 1}行：凭证字最多两个字符！`);
                    return;
                }
            }
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    //刷新 列表
                    this.pageList();
                }
            })
        },
        remove() {
            let _this = this;
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk() {
                    deleteAccount([_this.thisClickId]).then(res => {
                        if (res.code === 200) {
                            _this.$message.success('删除成功');
                            _this.reload();
                            setTimeout(() => {
                                _this.pageList();
                            }, 200)
                        }
                    })
                },
                onCancel() { },
            });
        },
        removes() {
            let _this = this;
            if (_this.selectedRowKeys.length < 1) {
                this.$message.warning('请选择一条数据');
                return;
            }
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk() {
                    let ids = _this.selectedRowKeys;
                    deleteAccount(ids).then(res => {
                        if (res.code === 200) {
                            _this.$message.success('删除成功');
                            _this.selectedRowKeys = [];
                            _this.reload();
                            setTimeout(() => {
                                _this.pageList();
                            }, 200)
                        }
                    }).catch(res => {
                        // this.$message.warning(res.message);
                    })
                },
                onCancel() { },
            });
        },
        onSelectChange(keys, rows) {
            this.selectedRowKeys = keys;
        }
    }
};
</script>
<style lang="less">
@import "~@/style/setting/business.less";
.category-table-container {
    height: calc(100% - 55px);
    border-bottom: none;
    overflow-y: auto;
    margin: 10px;
    .course-table-box {
        width: 100%;
        flex: 1;
        font-size: 12px;
    }

    //右键
    .contextmenu-box {
        .contextmenu {
            margin: 0;
            background: #fff;
            z-index: 3000;
            position: absolute;
            list-style-type: none;
            padding: 5px 0;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 400;
            color: #333;
            position: absolute;
            box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
        }

        .contextmenu li {
            margin: 0;
            padding: 7px 16px;
            cursor: pointer;
        }

        .contextmenu li:hover {
            background: #eee;
        }
    }

    .ant-table-tbody > tr > td {
        padding: 0px !important;
    }
}
</style>
 